#!/usr/bin/env python3
###
# @Author: Logan.Li
# @Gitee: https://gitee.com/attacker
# @email: admin@attacker.club
# @Date: 2025-03-14 09:40:30
# @LastEditTime: 2025-03-14 09:40:35
# @Description: 华为云ECS监控模块
###

import logging
from typing import Dict, List
from huaweicloud_sdk_ecs.v2 import *
from huaweicloud_sdk_ecs.v2.region.ecs_region import EcsRegion
from ..core import HuaweiCloudMonitor

class ECSMonitor(HuaweiCloudMonitor):
    """ECS监控类"""
    
    def __init__(self, config: Dict):
        super().__init__(config)
        self.namespace = "SYS.ECS"
        self.ecs_client = EcsClient.new_builder() \
            .with_credentials(self.credentials) \
            .with_region(EcsRegion.value_of(config['region'])) \
            .build()
            
    def list_instances(self) -> List[Dict]:
        """获取所有ECS实例"""
        try:
            request = ListServersDetailsRequest()
            response = self.ecs_client.list_servers_details(request)
            return response.to_dict().get('servers', [])
        except Exception as e:
            logging.error(f"获取ECS实例列表失败: {e}")
            return []
            
    def get_instance_metrics(self, instance_id: str) -> Dict:
        """获取实例监控指标
        
        Args:
            instance_id: 实例ID
        """
        dimensions = [{
            "name": "instance_id",
            "value": instance_id
        }]
        
        metrics = {}
        metric_list = [
            ("cpu_util", "CPU使用率"),
            ("mem_util", "内存使用率"),
            ("disk_util", "磁盘使用率"),
            ("network_incoming_bytes_rate", "网络入流量"),
            ("network_outgoing_bytes_rate", "网络出流量")
        ]
        
        for metric_name, metric_desc in metric_list:
            data = self.get_metric_data(
                namespace=self.namespace,
                metric_name=metric_name,
                dimensions=dimensions
            )
            metrics[metric_desc] = data
            
        return metrics
        
    def monitor_all_instances(self) -> Dict:
        """监控所有ECS实例"""
        instances = self.list_instances()
        abnormal_instances = []
        
        for instance in instances:
            instance_id = instance['id']
            instance_name = instance.get('name', instance_id)
            
            # 获取实例指标
            metrics = self.get_instance_metrics(instance_id)
            
            # 检查异常指标
            for metric_name, data in metrics.items():
                if not data:
                    continue
                    
                # 获取最新数据点
                datapoints = data.get('datapoints', [])
                if not datapoints:
                    continue
                    
                latest = datapoints[-1]
                value = latest.get('average')
                
                # 根据不同指标判断异常
                is_abnormal = False
                if metric_name == "CPU使用率" and value > 80:
                    is_abnormal = True
                elif metric_name == "内存使用率" and value > 85:
                    is_abnormal = True
                elif metric_name == "磁盘使用率" and value > 90:
                    is_abnormal = True
                
                if is_abnormal:
                    abnormal_instances.append({
                        'id': instance_id,
                        'name': instance_name,
                        'metric': metric_name,
                        'value': value,
                        'time': latest.get('timestamp')
                    })
        
        # 聚合监控结果
        result = {
            'total_instances': len(instances),
            'abnormal_count': len(abnormal_instances),
            'top_abnormal': sorted(
                abnormal_instances,
                key=lambda x: x['value'],
                reverse=True
            )[:5]  # 只返回最异常的前5个实例
        }
        
        return result
